package org.example.road.learn01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.internal.SystemPropertyUtil;
import lombok.extern.slf4j.Slf4j;
import sun.misc.Signal;
import sun.misc.SignalHandler;

import java.net.InetSocketAddress;

@Slf4j
public class Quit1 {

    private static final Integer THREADS = Math.max(1, SystemPropertyUtil.getInt(
            "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

    public static void main(String[] args) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(THREADS, new DefaultThreadFactory("server-acceptor"));
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(THREADS, new DefaultThreadFactory("server-worker"));
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.handler(new LoggingHandler(LogLevel.INFO));
        bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            }
        });
        try {
            final ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress("localhost", 8080)).sync();
            final Channel channel = channelFuture.channel();
            // jvm优雅退出，不能响应强制退出
            Runtime.getRuntime().addShutdownHook(new Thread(()->{
                log.info("优雅推出netty之前");
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                log.info("优雅退出netty之后");
            }));

            Signal sig = new Signal("TERM");
            Signal.handle(sig, new SignalHandler() {
                @Override
                public void handle(Signal signal) {
                    log.info("响应kill -9信号，优雅推出netty之前");
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                    log.info("优雅退出netty之后");
                }
            });

            log.info("服务启动成功");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("main线程退出");
    }
}
